package com.itcast.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itcast.yygh.hosp.repository.DepartmentRepository;
import com.itcast.yygh.hosp.service.DepartmentService;
import com.itcast.yygh.model.model.hosp.Department;
import com.itcast.yygh.model.vo.hosp.DepartmentQueryVo;
import com.itcast.yygh.model.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    //引入依赖
    @Resource
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> map) {
        //1.获取map中的科室对象
        Department department = JSONObject.parseObject(JSONObject.toJSONString(map), Department.class);
        //2.根据科室中的医院编码和部门编码查询mongo
        Department oldDepartment = departmentRepository.findByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        //3.如果查询到的对象有值就执行更新操作否则就执行添加操作
        if (Objects.isNull(oldDepartment)) {
            //执行保存操作
            //创建时间
            department.setCreateTime(new Date());
            //更新时间
            department.setUpdateTime(new Date());
            //是否删除
            department.setIsDeleted(0);
            //执行添加操作
            departmentRepository.save(department);
        } else {
            //执行更新操作
            //id
            department.setId(oldDepartment.getId());
            //设置创建时间
            department.setCreateTime(oldDepartment.getCreateTime());
            //更新时间
            department.setUpdateTime(new Date());
            //是否删除
            department.setIsDeleted(oldDepartment.getIsDeleted());
            //执行更新操作
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> findPage(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        //1.根据字段进行排序
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //2.设置分页需要条件  当前页 每页显示的条数  排序规则
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        //3.设置查询条件
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);
        //4.创建查询条件的实例和条件的匹配器
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);

        Example<Department> example = Example.of(department, matcher);
        //5.执行分页查询的方法
        Page<Department> pages = (Page<Department>) departmentRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        //1.先根据医院编号和科室编号查询数据库
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        //2.如果对象补位null就执行删除操作
        if (null != department) {
            departmentRepository.deleteById(department.getId());
        }
    }

    /*//根据医院编号，查询医院所有科室列表
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //0.创建list集合，用于最终数据封装
        List<DepartmentVo> result = new ArrayList<>();

        //1.根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        //查询库中的数据，获取所有科室列表 departmentList
        List<Department> departmentList = departmentRepository.findAll(example);

        //根据大科室编号  bigcode 分组，获取每个大科室里面下级子科室
        Map<String, List<Department>> departmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //2.对科室数据进行处理将大部门的数据和小部门的数据封装到一个科室对象中
        //遍历map集合 departmentMap 将大部门封装到集合对象中
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            //获取大科室编号
            String bigcode = entry.getKey();
            //大科室编号对应的全局数据
            List<Department> deparment1List = entry.getValue();
            //封装大科室
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepcode(bigcode);
            departmentVo1.setDepname(deparment1List.get(0).getBigname());

            //封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department : deparment1List) {
                DepartmentVo departmentVo2 = new DepartmentVo();
                departmentVo2.setDepcode(department.getDepcode());
                departmentVo2.setDepname(department.getDepname());
                //封装到list集合
                children.add(departmentVo2);
            }
            //把小科室list集合放到大科室children里面
            departmentVo1.setChildren(children);
            //放到最终result里面
            result.add(departmentVo1);
        }
        //返回
        return result;
    }*/

    @Override
    public List<DepartmentVo> findDeptTree(String hosCode) {
        //0.创建list集合，用于最终数据封装
        List<DepartmentVo> result = new ArrayList<>();

        //1.根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hosCode);
        Example<Department> example = Example.of(departmentQuery);
        //查询库中的数据，获取所有科室列表 departmentList
        List<Department> departmentList = departmentRepository.findAll(example);

        //根据大科室编号  bigcode 分组，获取每个大科室里面下级子科室
        Map<String, List<Department>> departmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //2.对科室数据进行处理将大部门的数据和小部门的数据封装到一个科室对象中
        departmentMap.forEach((bigcode, depList) -> {
            //封装大科室
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepcode(bigcode);
            departmentVo1.setDepname(depList.get(0).getBigname());

            //封装小科室
            List<DepartmentVo> children = depList.stream()
                    .map(department -> {
                        DepartmentVo depVo = new DepartmentVo();
                        depVo.setDepcode(department.getDepcode());
                        depVo.setDepname(department.getDepname());
                        return depVo;
                    })
                    .collect(Collectors.toList());
            //3.封装子部门列表数据到父部门对象中
            departmentVo1.setChildren(children);
            //将父部门对象封装进结果集
            result.add(departmentVo1);
        });
        //返回结果集
        return result;
    }

    //根据科室编号，和医院编号，查询科室名称
    @Override
    public String getDepName(String hoscode, String depcode) {
        //查询单个科室信息
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        if(department != null) {
            return department.getDepname();
        }
        return null;
    }

    //实现方法：根据医院编号 和 科室编号获取科室数据
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
    }
}
